package yagoMarried;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import triples.TriplesProcessor;

//because yago did not provide which document is this sentence located, we have to find out where the sentence is located in
//basic algorithm
//suppose S is a sentence A is the article
// the basic idea is each word in S can be found continue in A
public class SentenceLookUp {
	
	public static HashMap<String,ArrayList<String>> map;
	public static String replace(String inputStr, String replaceStr) { 
        Pattern p = Pattern.compile(" +"); 
        Matcher m = p.matcher(inputStr); 
        replaceStr=" ";
        return m.replaceAll(replaceStr); 
   }
	public static String cleanString(String s){
		//s= UtfToASC.filterNonAscii(s);
		s = s.replaceAll("\n", " ");
		s = s.trim();
		s = replace(s,null);
		
		return s;
	}
	
	public static ArrayList<String> str2list(String s){
		 s = cleanString(s);
		 ArrayList<String> list = new ArrayList<String>();
		 String [] ss = s.split(" ");
		 for(String a:ss){
			 list.add(a);
		 }
		 return list;
	}
	
	
	public static boolean strequal(String t,String s){
		
		//System.out.println("t:s:"+t+","+s);
		if( t.indexOf(s)>-1){
			return true;
		}else{
			return false;
		}
		
	}
	
	public static int indexOf(String s,ArrayList<String> ts, int start){
		if( start>=ts.size()){
			return -1;
		}
		int i =0;
		if( start<0){
			i =0;
		}else{
			i = start;
		}
		
		for(int j=i;j<ts.size();j++){
			if( strequal(ts.get(j),s)){
				//System.out.println(ts.get(j)+","+s);
				return j;
			}
		}
		return -1;
		
	}
	
	public static boolean find(String sentence,ArrayList<String> ts){
		ArrayList<String> ss = str2list(sentence);
		//ArrayList<String> ts = str2list(text);
		
		int start = -1;
		String start_word = ss.get(0);
		//System.out.println("start word:"+start_word);
		start = indexOf( start_word,ts,start);
		//System.out.println("start:"+start);
		while( start!=-1 ){
			//if(findOne(ss,ts,start)){
			if(findOne_1(ss,ts,start)){
				return true;
			}else{
				start = indexOf(start_word,ts,start+1);
			}
		}
		
		
		return false;
	}
	//after finding the jth word in text is equal to the start word of sentence, then check wether words in sentence could be found sequentially in this sentence
	public static boolean findOne(ArrayList<String> ss,ArrayList<String> ts, int start){
		
		int winsize =1;
		//System.out.println("in findone:"+start);
		int win =start;//win is the center of the window
		for( int i =0; i<ss.size();i++){
			String word = ss.get(i);
			int res = windowContain(word,win,winsize,ts);
			if( res ==-1000){
				return false;
			}else{
				win = win+res+1;
			}
			
		}
		
		return true;
	}
	
	//after finding the jth word in text is equal to the start word of sentence, then check wether words in sentence could be found sequentially in this sentence
	//allows one error
	public static boolean findOne_1(ArrayList<String> ss,ArrayList<String> ts, int start){
			
			int winsize =1;
			int error_count=0;
			//System.out.println("in findone:"+start);
			int win =start;//win is the center of the window
			for( int i =0; i<ss.size();i++){
				String word = ss.get(i);
				int res = windowContain(word,win,winsize,ts);
				if( res==-1000 ){
					error_count++;
				}
				
				if( (error_count>=3)&&(res ==-1000) ){
					return false;
				}else{
					if( res==-1000){
						win = win+1;
					}else{
						win = win+res+1;
					}
				}
				
			}
			
			return true;
		}
	
	//0 represent winceter match
	//+ represent wincenter+ match
	//- represent wincetern- match
	//-1000, no match
	public static int windowContain(String word, int win_center, int win_size,ArrayList<String>ts){
		
		if(win_center>=ts.size()){
			return -1000;
		}
		
		if( strequal(ts.get(win_center),word)){
			return 0;
		}
		
		int left = win_center-win_size;
		if( left<0){
			left =0;
		}
		
		int right = win_center+win_size;
		if( right>=ts.size()){
			right = ts.size()-1;
		}
		
		for( int m =left;m<=right;m++){
			String tword = ts.get(m);
			if (strequal(tword,word)){
				return m-win_center;
			}
		}
		return -1000;
	}
	
	public static File[] getAllFiles(String dir){
		File directory = new File(dir);
        File[] files = directory.listFiles();
    //    System.out.println(files.length);
        for (int i = 0; i < files.length; i++) {
        //	System.out.println(i + ":" + files[i].getName() + ";;;"+ files[i].getAbsolutePath());
           //files[i].renameTo(new File(dir + i + files[i].getName()));
   
           
           //System.out.println(files[i].getName());
       }
       return files;
	}
	public static String getFileContents(String fileName) throws Exception {
	    File theFile = new File(fileName);
	    byte[] bytes = new byte[(int) theFile.length()];
	    InputStream in = new FileInputStream(theFile);
	    int m = 0, n = 0;
	    while (m < bytes.length) {
		n = in.read(bytes, m, bytes.length - m);
		m += n;
	    }
	    in.close();
	    
	    // using default encoding, this is probably what BufferedReader.readLine does anyway
	    return new String(bytes); 
	}
	
	public static void loadFile(String Dir){
		try {
			
			if(map==null){
				System.out.println("Load File in Sentence Lookup!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
				map = new HashMap<String,ArrayList<String>>();
				File[] files = getAllFiles(Dir);
				for( int i=0; i<files.length;i++){
					String abspath = files[i].getAbsolutePath();
					String content = getFileContents(abspath);
					ArrayList<String> ts =str2list(content);
					map.put(abspath, ts);
			
			
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public static String lookInDir(String sen, String Dir){
		
		loadFile(Dir);
		for(String path: map.keySet()){
			ArrayList<String> content = map.get(path);
			boolean result = find(sen,content);
			if( result==true ){
				return path;
			}
		}
		return null;
	}
	public static void main(String[] args) throws Exception{
		
		String s = "a 2-2  World Cup qualifying draw against Austria in September 2004 , his place";
		String text = TriplesProcessor.getFileContents("/Users/leiyao/cmput696/ttt.txt");
		/*s = SentenceLookUp.cleanString(s);
		String[]ss=s.split(" ");
		int i =0;
		for(String a: ss){
			System.out.println(i+":"+a);
		}
		System.out.println(ss.length);*/
		
		//System.out.println(SentenceLookUp.find(s, text));
		
		//System.out.println(text);
		
		
	}

}
